from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

import models
from auth import get_current_active_user
from db import get_db
from models import Product
from schemas import ProductPublic

router = APIRouter(prefix="/api/product", tags=["产品"])

@router.get("/all")
def get_product_all(db: Session = Depends(get_db)):
    records=db.query(Product).all()
    data_list=[]
    for record in records:
        item=ProductPublic.from_orm(record)
        item.image=f"http://localhost:8000/{item.image}"
        data_list.append(item)
    return data_list

@router.get("/{product_id}")
def get_product(current_user: Annotated[models.User, Depends(get_current_active_user)],product_id: int, db: Session = Depends(get_db)):
  product = db.query(Product).filter(Product.id == product_id).first()
  if product is None:
    raise HTTPException(status_code=404, detail="product not found")
  product.image=f"http://localhost:8000/{product.image}"
  return product



@router.get("/search/iphone", response_model=ProductPublic)
def get_product_by_name(current_user: Annotated[models.User, Depends(get_current_active_user)],db: Session = Depends(get_db)):
    product = db.query(Product).filter(Product.name == prduct_number).first()
    if product is None:
        raise HTTPException(status_code=404, detail="Product not found")
    product_public = ProductPublic.from_orm(product)
    product_public.image = f"http://localhost:8000/{product_public.image}"
    return product_public








